// main.go
package main

import (
	"context"
	"file-manager/handlers"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	// === 1. 设置 Gin 模式 ===
	gin.SetMode(gin.ReleaseMode) // 强制生产模式

	// === 2. 从环境变量读取配置 ===
	port := os.Getenv("PORT")
	if port == "" {
		port = "8888"
	}
	uploadDir := os.Getenv("UPLOAD_DIR")
	if uploadDir == "" {
		uploadDir = "./uploads"
	}

	// 创建上传目录
	if err := os.MkdirAll(uploadDir, 0755); err != nil {
		log.Fatal("Failed to create upload directory:", err)
	}

	// === 3. 初始化 Gin（显式控制中间件）===
	r := gin.New()
	r.Use(gin.Logger(), gin.Recovery())

	// === 4. 设置可信代理（根据部署环境选择）===
	// 场景 A: 直接暴露（无 Nginx/LB）→ 禁用代理信任
	// r.SetTrustedProxies(nil)

	// 场景 B: 有 Nginx / 云 LB（推荐）
	// 假设 Nginx 在同一主机或内网，信任 127.0.0.1 和私有网段
	if err := r.SetTrustedProxies([]string{
		"127.0.0.1",  // 本地 Nginx
		"10.0.0.0/8", // AWS/Aliyun 内网
		"172.16.0.0/12",
		"192.168.0.0/16",
		"::1", // IPv6 localhost
	}); err != nil {
		log.Fatal("Failed to set trusted proxies:", err)
	}

	// 设置最大内存（用于 multipart 表单）
	r.MaxMultipartMemory = 10 << 20 // 10MB

	// === 5. 注册路由 ===
	api := r.Group("/api")
	{
		// 文件操作
		api.GET("/files", handlers.File_Handlers.ListFiles)
		api.POST("/files", handlers.File_Handlers.CreateFile)
		api.DELETE("/files/:id", handlers.File_Handlers.DeleteFile)
		api.PUT("/files/:id/rename", handlers.File_Handlers.RenameFile)
		api.GET("/files/:id/preview", handlers.File_Handlers.PreviewFile)
		api.GET("/files/:id/download", handlers.File_Handlers.DownloadFile)

		// 上传
		api.POST("/upload/chunk", handlers.Upload_Handlers.UploadChunk)
		api.POST("/upload/complete", handlers.Upload_Handlers.CompleteUpload)
		api.GET("/upload/status/:fileId", handlers.Upload_Handlers.UploadStatus)
		api.GET("/upload/verify", handlers.Upload_Handlers.VerifyUpload)
		api.POST("/upload/drag", handlers.Upload_Handlers.DragUpload)

		// 文件夹
		api.POST("/folders", handlers.Folder_Handlers.CreateFolder)
	}

	// 启动清理任务
	go handlers.Upload_Handlers.CleanupOldUploads()

	// === 6. 优雅启动与关闭 ===
	srv := &http.Server{
		Addr:    ":" + port,
		Handler: r,
	}

	// 启动服务
	go func() {
		fmt.Printf("Server starting on :%s\n", port)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("Server failed to start: %v", err)
		}
	}()

	// 等待中断信号（如 Ctrl+C）
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	fmt.Println("Shutting down server...")

	// 优雅关闭（5秒超时）
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server forced to shutdown:", err)
	}
	fmt.Println("Server exited gracefully")
}
